package org.jdcenter.jndi.context;

import java.util.concurrent.ConcurrentHashMap;

import javax.naming.Binding;
import javax.naming.Name;
import javax.naming.NameParser;
import javax.naming.NamingException;

import org.jdcenter.jndi.naming.JDSNameParser;

public abstract class ContextAdapter extends ContextImpl implements AbstractContext{
	
	protected ConcurrentHashMap<String,ContextAdapter> contexts 
			= new ConcurrentHashMap<String,ContextAdapter>();
	protected ConcurrentHashMap<String,Object> objects
			= new ConcurrentHashMap<String,Object>();
	protected ContextAdapter previous_context = null;
	protected String namespace = null;
	protected Name relative_name = null;
	protected int posn = 0;
	
	protected NameParser parser = null;
	
	public ContextAdapter(){
		this(ProxyContext.getRootNamespace());
	}
	public ContextAdapter(String namespace){
		this(namespace,new JDSNameParser());
	}
	public ContextAdapter(String namespace,NameParser parser){
		this.namespace = namespace;		
		this.parser = parser;
		try {
			this.relative_name = parser.parse(namespace);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public ContextAdapter(Name name,ContextAdapter previous_context){
		this.previous_context = previous_context;
		this.parser = previous_context.getNameParser();		
		this.posn = previous_context.getPosn()+1;
		this.namespace = name.get(this.posn);
		try {
			this.relative_name = this.parser.parse(this.namespace);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void setPosn(int posn){
		this.posn = posn;
	}
	
	public int getPosn(){
		return this.posn;
	}
	public NameParser getNameParser(){
		return this.parser;
	}
	public void bind(String name, Object obj) throws NamingException {
        bind(parser.parse(name),obj);
    }

    public void rebind(String name, Object obj) throws NamingException {
        rebind(parser.parse(name),obj);
    }

    public void unbind(String name) throws NamingException {
        unbind(parser.parse(name));
    }

    public Object lookup(String name) throws NamingException {
    	return lookup(parser.parse(name));
    }

}
